#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
校园跑步提醒系统主程序
整合操场开放时间和天气数据，生成跑步提醒
"""

import os
import sys
from datetime import datetime
import json

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from src.crawler import SportFieldCrawler
from src.weather import WeatherService
from src.config import (
    SCHOOL_NAME,
    PLAYGROUND_URL,
    WEATHER_API_KEY,
    CITY,
    DATA_DIR,
    SUITABLE_TEMPERATURE_RANGE,
    SUITABLE_HUMIDITY_MAX,
    MORNING_SLOTS,
    AFTERNOON_SLOTS
)

class RunningReminder:
    """跑步提醒类"""
    
    def __init__(self):
        """初始化跑步提醒系统"""
        self.school_name = SCHOOL_NAME
        self.data_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), DATA_DIR.lstrip('../'))
        os.makedirs(self.data_dir, exist_ok=True)
        
        # 初始化爬虫和天气服务
        self.crawler = SportFieldCrawler()
        self.weather_service = WeatherService(api_key=WEATHER_API_KEY, city=CITY)
    
    def get_today_open_hours(self):
        """获取今日操场开放时间
        
        Returns:
            dict: 今日开放时间信息
        """
        # 获取今日星期几
        weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        today_weekday = weekdays[datetime.now().weekday()]
        
        # 获取开放时间数据
        open_hours_data = self.crawler.get_open_hours()
        
        # 提取今日开放时间
        today_hours = open_hours_data.get('hours', {}).get(today_weekday, {})
        
        return {
            'date': datetime.now().strftime('%Y-%m-%d'),
            'weekday': today_weekday,
            'time_slots': today_hours.get('time_slots', []),
            'note': today_hours.get('note', '无特别说明'),
            'crawl_time': open_hours_data.get('crawl_time', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        }
    
    def generate_running_reminder(self):
        """生成跑步提醒
        
        Returns:
            dict: 跑步提醒信息
        """
        # 获取今日开放时间
        today_open_hours = self.get_today_open_hours()
        
        # 获取天气数据
        weather_data = self.weather_service.get_weather()
        
        # 判断天气是否适合跑步
        suitable_for_running, weather_advice = self.weather_service.is_suitable_for_running(weather_data)
        
        # 获取当前时间
        current_time = datetime.now()
        current_time_str = current_time.strftime('%H:%M')
        
        # 检查当前是否在开放时间内
        is_open_now = False
        current_time_obj = current_time.time()
        
        for time_slot in today_open_hours['time_slots']:
            start_time = datetime.strptime(time_slot['start'], '%H:%M').time()
            end_time = datetime.strptime(time_slot['end'], '%H:%M').time()
            
            if start_time <= current_time_obj <= end_time:
                is_open_now = True
                break
        
        # 寻找今天合适的跑步时间段
        suitable_time_slots = []
        if suitable_for_running:
            for time_slot in today_open_hours['time_slots']:
                # 可以根据天气条件进一步过滤时间段
                # 例如：炎热天气推荐早晨或傍晚
                start_time = time_slot['start']
                end_time = time_slot['end']
                
                # 使用配置文件中的时间段进行推荐
                start_hour = int(start_time.split(':')[0])
                morning_start, morning_end = map(lambda x: int(x.split(':')[0]), MORNING_SLOTS)
                afternoon_start, afternoon_end = map(lambda x: int(x.split(':')[0]), AFTERNOON_SLOTS)
                
                if morning_start <= start_hour < morning_end:
                    recommendation = '早晨空气清新，适合跑步'
                elif afternoon_start <= start_hour < afternoon_end:
                    recommendation = '傍晚温度适宜，是跑步的好时机'
                else:
                    recommendation = '该时间段可以跑步'
                
                suitable_time_slots.append({
                    'start': start_time,
                    'end': end_time,
                    'recommendation': recommendation
                })
        
        # 生成提醒信息
        reminder = {
            'school': self.school_name,
            'date': today_open_hours['date'],
            'weekday': today_open_hours['weekday'],
            'current_time': current_time_str,
            'playground_open': today_open_hours['time_slots'],
            'is_open_now': is_open_now,
            'weather': weather_data,
            'suitable_for_running': suitable_for_running,
            'weather_advice': weather_advice,
            'suitable_time_slots': suitable_time_slots,
            'reminder_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        
        return reminder
    
    def format_reminder(self, reminder):
        """格式化提醒信息为可读文本
        
        Args:
            reminder (dict): 跑步提醒信息
        
        Returns:
            str: 格式化后的提醒文本
        """
        text = []
        text.append(f"📢 {self.school_name}跑步提醒")
        text.append(f"📅 {reminder['date']} {reminder['weekday']}")
        text.append(f"🕒 当前时间: {reminder['current_time']}")
        text.append("")
        
        # 操场开放信息
        text.append("🏃 操场开放时间:")
        if reminder['playground_open']:
            for slot in reminder['playground_open']:
                text.append(f"  - {slot['start']} ~ {slot['end']}")
        else:
            text.append("  - 今日不开放")
        
        text.append(f"  当前{'开放中' if reminder['is_open_now'] else '未开放'}")
        text.append("")
        
        # 天气信息
        text.append("🌤️ 今日天气:")
        text.append(f"  - 天气状况: {reminder['weather']['weather']}")
        text.append(f"  - 温度: {reminder['weather']['temperature']}°C")
        text.append(f"  - 湿度: {reminder['weather']['humidity']}%")
        text.append(f"  - 风力: {reminder['weather']['wind_power']}")
        text.append("")
        
        # 跑步建议
        text.append("💡 跑步建议:")
        text.append(f"  {reminder['weather_advice']}")
        
        if reminder['suitable_time_slots']:
            text.append("\n⏰ 推荐跑步时间段:")
            for slot in reminder['suitable_time_slots']:
                text.append(f"  - {slot['start']} ~ {slot['end']}: {slot['recommendation']}")
        
        text.append("")
        text.append("💪 坚持运动，保持健康！")
        text.append(f"更新时间: {reminder['reminder_time']}")
        
        return '\n'.join(text)
    
    def save_reminder(self, reminder):
        """保存提醒信息到文件
        
        Args:
            reminder (dict): 跑步提醒信息
        """
        filename = os.path.join(self.data_dir, f"running_reminder_{datetime.now().strftime('%Y%m%d')}.json")
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(reminder, f, ensure_ascii=False, indent=2)
            print(f"提醒信息已保存到 {filename}")
        except Exception as e:
            print(f"保存提醒信息时出错: {e}")
    
    def run(self):
        """运行跑步提醒系统"""
        print(f"正在生成{self.school_name}今日跑步提醒...")
        
        try:
            # 生成提醒
            reminder = self.generate_running_reminder()
            
            # 保存提醒
            self.save_reminder(reminder)
            
            # 格式化并显示提醒
            formatted_reminder = self.format_reminder(reminder)
            print("\n" + "="*50)
            print(formatted_reminder)
            print("="*50)
            
            return formatted_reminder
        except Exception as e:
            print(f"生成跑步提醒时出错: {e}")
            return None

def main():
    """主函数"""
    # 直接从配置文件读取参数，无需手动传入
    
    # 创建并运行跑步提醒系统
    reminder_system = RunningReminder()
    reminder_system.run()

if __name__ == '__main__':
    main()